﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using PaliReaderUtils;
using System.Text.RegularExpressions;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections.Generic;
using CSCDBookConverter.contentsDSTableAdapters;
using System.Data.SqlServerCe;
using CSCDBookConverter.Utilities;

namespace CSCDBookConverter
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainWnd : System.Windows.Forms.Form
	{
		private ArrayList m_arrChaptersList=null;
		private int m_nParentNodeID=0;
		private int m_nNodeCounter=1;
		private int m_nZipFileIndex=0;
		private int m_nC13NodeID=-1;
		private byte m_nLibFileIndex=1;
		private int m_nParagraphID=0;

        private int m_nFileID;
        contentsDS.NodesRow objPrevNode = null;

		ZipOutputStream m_objLibraryStream;

		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox ctlCSCDFolder;
		private System.Windows.Forms.Button ctlCSCDBrowse;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox ctlDestFolder;
		private System.Windows.Forms.Button ctlDestFolderBrowse;
		private System.Windows.Forms.ErrorProvider ctlErrorProvider;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox ctlPlatform;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.ComboBox ctlDiffsHandling;
		private System.Windows.Forms.FolderBrowserDialog ctlBrowseFolder;
		private System.Windows.Forms.Label ctlMessage;
		private System.Windows.Forms.ProgressBar ctlConversionProgress;
		private System.Windows.Forms.Button ctlStartConversion2;
		private System.Windows.Forms.CheckBox ctlVinaya;
		private System.Windows.Forms.CheckBox ctlSutta;
		private System.Windows.Forms.CheckBox ctlAbidhamma;
		private System.Windows.Forms.CheckBox ctlAtthakatha;
		private System.Windows.Forms.CheckBox ctlTika;
		private System.Windows.Forms.CheckBox ctlOther;
		private System.Windows.Forms.CheckBox ctlMula;
		private System.Windows.Forms.CheckBox ctlOtherContent;
		private System.Windows.Forms.CheckBox ctlPagesVRI;
		private System.Windows.Forms.CheckBox ctlPagesPTS;
		private System.Windows.Forms.CheckBox ctlPagesMyanmar;
		private System.Windows.Forms.CheckBox ctlPagesThai;
        private System.Windows.Forms.CheckBox ctlPagesOther;
        private contentsDS m_objDS;
        private FilesTableAdapter m_objFilesTA;
        private NodesTableAdapter m_objNodesTA;
        private CollectionsTableAdapter m_objCollectionsTA;
        private PTSPagesTableAdapter m_objPTSPagesTA;
        private CheckBox ctlGenerateFiles;
        private Button button1;
        private TextBox ctlDictionaryPath;
        private ComboBox ctlDictionary;
        private DictionaryContentTableAdapter m_objContentsTA;
        private DictionariesTableAdapter m_objDictionariesTA;
        private Button ctlPrepare;
        private TextBox ctlHTMLPEDDest;
        private TextBox ctlHTMLPEDSource;
        private Button button2;
        private IContainer components;

		public MainWnd()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this.label1 = new System.Windows.Forms.Label();
            this.ctlCSCDFolder = new System.Windows.Forms.TextBox();
            this.ctlCSCDBrowse = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.ctlDestFolder = new System.Windows.Forms.TextBox();
            this.ctlDestFolderBrowse = new System.Windows.Forms.Button();
            this.ctlErrorProvider = new System.Windows.Forms.ErrorProvider(this.components);
            this.label3 = new System.Windows.Forms.Label();
            this.ctlPlatform = new System.Windows.Forms.ComboBox();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.ctlDiffsHandling = new System.Windows.Forms.ComboBox();
            this.ctlBrowseFolder = new System.Windows.Forms.FolderBrowserDialog();
            this.ctlMessage = new System.Windows.Forms.Label();
            this.ctlConversionProgress = new System.Windows.Forms.ProgressBar();
            this.ctlStartConversion2 = new System.Windows.Forms.Button();
            this.ctlVinaya = new System.Windows.Forms.CheckBox();
            this.ctlSutta = new System.Windows.Forms.CheckBox();
            this.ctlAbidhamma = new System.Windows.Forms.CheckBox();
            this.ctlOther = new System.Windows.Forms.CheckBox();
            this.ctlAtthakatha = new System.Windows.Forms.CheckBox();
            this.ctlTika = new System.Windows.Forms.CheckBox();
            this.ctlMula = new System.Windows.Forms.CheckBox();
            this.ctlOtherContent = new System.Windows.Forms.CheckBox();
            this.ctlPagesPTS = new System.Windows.Forms.CheckBox();
            this.ctlPagesVRI = new System.Windows.Forms.CheckBox();
            this.ctlPagesMyanmar = new System.Windows.Forms.CheckBox();
            this.ctlPagesThai = new System.Windows.Forms.CheckBox();
            this.ctlPagesOther = new System.Windows.Forms.CheckBox();
            this.ctlGenerateFiles = new System.Windows.Forms.CheckBox();
            this.ctlDictionaryPath = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.ctlDictionary = new System.Windows.Forms.ComboBox();
            this.m_objDS = new CSCDBookConverter.contentsDS();
            this.m_objFilesTA = new CSCDBookConverter.contentsDSTableAdapters.FilesTableAdapter();
            this.m_objNodesTA = new CSCDBookConverter.contentsDSTableAdapters.NodesTableAdapter();
            this.m_objCollectionsTA = new CSCDBookConverter.contentsDSTableAdapters.CollectionsTableAdapter();
            this.m_objPTSPagesTA = new CSCDBookConverter.contentsDSTableAdapters.PTSPagesTableAdapter();
            this.m_objContentsTA = new CSCDBookConverter.contentsDSTableAdapters.DictionaryContentTableAdapter();
            this.m_objDictionariesTA = new CSCDBookConverter.contentsDSTableAdapters.DictionariesTableAdapter();
            this.ctlHTMLPEDSource = new System.Windows.Forms.TextBox();
            this.ctlHTMLPEDDest = new System.Windows.Forms.TextBox();
            this.ctlPrepare = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.ctlErrorProvider)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.m_objDS)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(7, 14);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(73, 21);
            this.label1.TabIndex = 0;
            this.label1.Text = "CSCD folder:";
            // 
            // ctlCSCDFolder
            // 
            this.ctlCSCDFolder.Location = new System.Drawing.Point(113, 14);
            this.ctlCSCDFolder.Name = "ctlCSCDFolder";
            this.ctlCSCDFolder.Size = new System.Drawing.Size(227, 20);
            this.ctlCSCDFolder.TabIndex = 1;
            this.ctlCSCDFolder.Text = "D:\\distr\\PaliCD";
            this.ctlCSCDFolder.Validating += new System.ComponentModel.CancelEventHandler(this.ctlCSCDFolder_Validating);
            // 
            // ctlCSCDBrowse
            // 
            this.ctlCSCDBrowse.CausesValidation = false;
            this.ctlCSCDBrowse.Location = new System.Drawing.Point(360, 7);
            this.ctlCSCDBrowse.Name = "ctlCSCDBrowse";
            this.ctlCSCDBrowse.Size = new System.Drawing.Size(80, 28);
            this.ctlCSCDBrowse.TabIndex = 2;
            this.ctlCSCDBrowse.Text = "Browse...";
            this.ctlCSCDBrowse.Click += new System.EventHandler(this.ctlCSCDBrowse_Click);
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(7, 49);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(100, 20);
            this.label2.TabIndex = 3;
            this.label2.Text = "Destination folder:";
            // 
            // ctlDestFolder
            // 
            this.ctlDestFolder.Location = new System.Drawing.Point(113, 49);
            this.ctlDestFolder.Name = "ctlDestFolder";
            this.ctlDestFolder.Size = new System.Drawing.Size(227, 20);
            this.ctlDestFolder.TabIndex = 4;
            this.ctlDestFolder.Text = "C:\\Documents and Settings\\Pavel Bure\\My Documents\\Visual Studio 2008\\Projects\\Pal" +
                "iReader\\canon";
            this.ctlDestFolder.Validating += new System.ComponentModel.CancelEventHandler(this.ctlDestFolder_Validating);
            // 
            // ctlDestFolderBrowse
            // 
            this.ctlDestFolderBrowse.CausesValidation = false;
            this.ctlDestFolderBrowse.Location = new System.Drawing.Point(360, 49);
            this.ctlDestFolderBrowse.Name = "ctlDestFolderBrowse";
            this.ctlDestFolderBrowse.Size = new System.Drawing.Size(80, 27);
            this.ctlDestFolderBrowse.TabIndex = 5;
            this.ctlDestFolderBrowse.Text = "Browse...";
            this.ctlDestFolderBrowse.Click += new System.EventHandler(this.ctlDestFolderBrowse_Click);
            // 
            // ctlErrorProvider
            // 
            this.ctlErrorProvider.ContainerControl = this;
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(7, 76);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(100, 14);
            this.label3.TabIndex = 6;
            this.label3.Text = "Platform:";
            this.label3.Visible = false;
            // 
            // ctlPlatform
            // 
            this.ctlPlatform.CausesValidation = false;
            this.ctlPlatform.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.ctlPlatform.Items.AddRange(new object[] {
            "Pocket PC",
            "Desktop PC"});
            this.ctlPlatform.Location = new System.Drawing.Point(113, 76);
            this.ctlPlatform.Name = "ctlPlatform";
            this.ctlPlatform.Size = new System.Drawing.Size(167, 21);
            this.ctlPlatform.TabIndex = 7;
            this.ctlPlatform.Visible = false;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(7, 111);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(106, 21);
            this.label4.TabIndex = 9;
            this.label4.Text = "Page numbers:";
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(7, 139);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(106, 27);
            this.label5.TabIndex = 10;
            this.label5.Text = "Differences between tipitaka editions: ";
            // 
            // ctlDiffsHandling
            // 
            this.ctlDiffsHandling.CausesValidation = false;
            this.ctlDiffsHandling.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.ctlDiffsHandling.Items.AddRange(new object[] {
            "Leave intact",
            "Strip book abbreviations only",
            "Strip completely"});
            this.ctlDiffsHandling.Location = new System.Drawing.Point(113, 146);
            this.ctlDiffsHandling.Name = "ctlDiffsHandling";
            this.ctlDiffsHandling.Size = new System.Drawing.Size(227, 21);
            this.ctlDiffsHandling.TabIndex = 11;
            // 
            // ctlMessage
            // 
            this.ctlMessage.Location = new System.Drawing.Point(7, 326);
            this.ctlMessage.Name = "ctlMessage";
            this.ctlMessage.Size = new System.Drawing.Size(406, 28);
            this.ctlMessage.TabIndex = 13;
            // 
            // ctlConversionProgress
            // 
            this.ctlConversionProgress.Location = new System.Drawing.Point(7, 361);
            this.ctlConversionProgress.Name = "ctlConversionProgress";
            this.ctlConversionProgress.Size = new System.Drawing.Size(406, 20);
            this.ctlConversionProgress.TabIndex = 14;
            // 
            // ctlStartConversion2
            // 
            this.ctlStartConversion2.Location = new System.Drawing.Point(7, 274);
            this.ctlStartConversion2.Name = "ctlStartConversion2";
            this.ctlStartConversion2.Size = new System.Drawing.Size(433, 41);
            this.ctlStartConversion2.TabIndex = 15;
            this.ctlStartConversion2.Text = "Start conversion";
            this.ctlStartConversion2.Click += new System.EventHandler(this.ctlStartConversion2_Click);
            // 
            // ctlVinaya
            // 
            this.ctlVinaya.Checked = true;
            this.ctlVinaya.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlVinaya.Location = new System.Drawing.Point(7, 173);
            this.ctlVinaya.Name = "ctlVinaya";
            this.ctlVinaya.Size = new System.Drawing.Size(160, 21);
            this.ctlVinaya.TabIndex = 16;
            this.ctlVinaya.Text = "Include Vinaya pitaka";
            // 
            // ctlSutta
            // 
            this.ctlSutta.Checked = true;
            this.ctlSutta.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlSutta.Location = new System.Drawing.Point(7, 201);
            this.ctlSutta.Name = "ctlSutta";
            this.ctlSutta.Size = new System.Drawing.Size(153, 21);
            this.ctlSutta.TabIndex = 17;
            this.ctlSutta.Text = "Include Sutta Pitaka";
            // 
            // ctlAbidhamma
            // 
            this.ctlAbidhamma.Checked = true;
            this.ctlAbidhamma.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlAbidhamma.Location = new System.Drawing.Point(167, 173);
            this.ctlAbidhamma.Name = "ctlAbidhamma";
            this.ctlAbidhamma.Size = new System.Drawing.Size(173, 21);
            this.ctlAbidhamma.TabIndex = 18;
            this.ctlAbidhamma.Text = "Include abidhamma pitaka";
            // 
            // ctlOther
            // 
            this.ctlOther.Checked = true;
            this.ctlOther.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlOther.Location = new System.Drawing.Point(167, 201);
            this.ctlOther.Name = "ctlOther";
            this.ctlOther.Size = new System.Drawing.Size(180, 21);
            this.ctlOther.TabIndex = 19;
            this.ctlOther.Text = "Include other texts";
            // 
            // ctlAtthakatha
            // 
            this.ctlAtthakatha.Checked = true;
            this.ctlAtthakatha.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlAtthakatha.Location = new System.Drawing.Point(107, 236);
            this.ctlAtthakatha.Name = "ctlAtthakatha";
            this.ctlAtthakatha.Size = new System.Drawing.Size(113, 37);
            this.ctlAtthakatha.TabIndex = 20;
            this.ctlAtthakatha.Text = "Include atthakatha";
            // 
            // ctlTika
            // 
            this.ctlTika.Checked = true;
            this.ctlTika.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlTika.Location = new System.Drawing.Point(227, 236);
            this.ctlTika.Name = "ctlTika";
            this.ctlTika.Size = new System.Drawing.Size(80, 37);
            this.ctlTika.TabIndex = 21;
            this.ctlTika.Text = "Include tika";
            // 
            // ctlMula
            // 
            this.ctlMula.Checked = true;
            this.ctlMula.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlMula.Location = new System.Drawing.Point(7, 236);
            this.ctlMula.Name = "ctlMula";
            this.ctlMula.Size = new System.Drawing.Size(93, 21);
            this.ctlMula.TabIndex = 22;
            this.ctlMula.Text = "Include mula";
            // 
            // ctlOtherContent
            // 
            this.ctlOtherContent.Checked = true;
            this.ctlOtherContent.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlOtherContent.Location = new System.Drawing.Point(307, 236);
            this.ctlOtherContent.Name = "ctlOtherContent";
            this.ctlOtherContent.Size = new System.Drawing.Size(86, 37);
            this.ctlOtherContent.TabIndex = 23;
            this.ctlOtherContent.Text = "Include other";
            // 
            // ctlPagesPTS
            // 
            this.ctlPagesPTS.Checked = true;
            this.ctlPagesPTS.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlPagesPTS.Location = new System.Drawing.Point(113, 111);
            this.ctlPagesPTS.Name = "ctlPagesPTS";
            this.ctlPagesPTS.Size = new System.Drawing.Size(47, 21);
            this.ctlPagesPTS.TabIndex = 24;
            this.ctlPagesPTS.Text = "PTS";
            // 
            // ctlPagesVRI
            // 
            this.ctlPagesVRI.Checked = true;
            this.ctlPagesVRI.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlPagesVRI.Location = new System.Drawing.Point(160, 111);
            this.ctlPagesVRI.Name = "ctlPagesVRI";
            this.ctlPagesVRI.Size = new System.Drawing.Size(40, 21);
            this.ctlPagesVRI.TabIndex = 25;
            this.ctlPagesVRI.Text = "VRI";
            // 
            // ctlPagesMyanmar
            // 
            this.ctlPagesMyanmar.Checked = true;
            this.ctlPagesMyanmar.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlPagesMyanmar.Location = new System.Drawing.Point(200, 111);
            this.ctlPagesMyanmar.Name = "ctlPagesMyanmar";
            this.ctlPagesMyanmar.Size = new System.Drawing.Size(67, 21);
            this.ctlPagesMyanmar.TabIndex = 26;
            this.ctlPagesMyanmar.Text = "Myanmar";
            // 
            // ctlPagesThai
            // 
            this.ctlPagesThai.Checked = true;
            this.ctlPagesThai.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlPagesThai.Location = new System.Drawing.Point(267, 111);
            this.ctlPagesThai.Name = "ctlPagesThai";
            this.ctlPagesThai.Size = new System.Drawing.Size(46, 21);
            this.ctlPagesThai.TabIndex = 27;
            this.ctlPagesThai.Text = "Thai";
            // 
            // ctlPagesOther
            // 
            this.ctlPagesOther.Checked = true;
            this.ctlPagesOther.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlPagesOther.Location = new System.Drawing.Point(313, 111);
            this.ctlPagesOther.Name = "ctlPagesOther";
            this.ctlPagesOther.Size = new System.Drawing.Size(54, 21);
            this.ctlPagesOther.TabIndex = 28;
            this.ctlPagesOther.Text = "Other";
            // 
            // ctlGenerateFiles
            // 
            this.ctlGenerateFiles.AutoSize = true;
            this.ctlGenerateFiles.Checked = true;
            this.ctlGenerateFiles.CheckState = System.Windows.Forms.CheckState.Checked;
            this.ctlGenerateFiles.Location = new System.Drawing.Point(322, 337);
            this.ctlGenerateFiles.Name = "ctlGenerateFiles";
            this.ctlGenerateFiles.Size = new System.Drawing.Size(91, 17);
            this.ctlGenerateFiles.TabIndex = 29;
            this.ctlGenerateFiles.Text = "Generate files";
            this.ctlGenerateFiles.UseVisualStyleBackColor = true;
            // 
            // ctlDictionaryPath
            // 
            this.ctlDictionaryPath.Location = new System.Drawing.Point(10, 406);
            this.ctlDictionaryPath.Name = "ctlDictionaryPath";
            this.ctlDictionaryPath.Size = new System.Drawing.Size(257, 20);
            this.ctlDictionaryPath.TabIndex = 30;
            this.ctlDictionaryPath.Text = "C:\\Program Files\\Chattha Sangayana Tipitaka 4.0\\Reference\\en\\pali-english-diction" +
                "ary.txt";
            this.ctlDictionaryPath.Visible = false;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(442, 404);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(90, 23);
            this.button1.TabIndex = 31;
            this.button1.Text = "Convert";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Visible = false;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // ctlDictionary
            // 
            this.ctlDictionary.DisplayMember = "Name";
            this.ctlDictionary.FormattingEnabled = true;
            this.ctlDictionary.Location = new System.Drawing.Point(274, 406);
            this.ctlDictionary.Name = "ctlDictionary";
            this.ctlDictionary.Size = new System.Drawing.Size(139, 21);
            this.ctlDictionary.TabIndex = 32;
            this.ctlDictionary.ValueMember = "DictionaryID";
            this.ctlDictionary.Visible = false;
            // 
            // m_objDS
            // 
            this.m_objDS.DataSetName = "contentsDS";
            this.m_objDS.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
            // 
            // m_objFilesTA
            // 
            this.m_objFilesTA.ClearBeforeFill = true;
            // 
            // m_objNodesTA
            // 
            this.m_objNodesTA.ClearBeforeFill = true;
            // 
            // m_objCollectionsTA
            // 
            this.m_objCollectionsTA.ClearBeforeFill = true;
            // 
            // m_objPTSPagesTA
            // 
            this.m_objPTSPagesTA.ClearBeforeFill = true;
            // 
            // m_objContentsTA
            // 
            this.m_objContentsTA.ClearBeforeFill = true;
            // 
            // m_objDictionariesTA
            // 
            this.m_objDictionariesTA.ClearBeforeFill = true;
            // 
            // ctlHTMLPEDSource
            // 
            this.ctlHTMLPEDSource.Location = new System.Drawing.Point(13, 443);
            this.ctlHTMLPEDSource.Name = "ctlHTMLPEDSource";
            this.ctlHTMLPEDSource.Size = new System.Drawing.Size(132, 20);
            this.ctlHTMLPEDSource.TabIndex = 33;
            this.ctlHTMLPEDSource.Text = "C:\\Documents and Settings\\Pavel Bure\\My Documents\\Visual Studio 2008\\Projects\\Rhy" +
                "sDavids\\RhysDavids.html";
            this.ctlHTMLPEDSource.Visible = false;
            // 
            // ctlHTMLPEDDest
            // 
            this.ctlHTMLPEDDest.Location = new System.Drawing.Point(160, 443);
            this.ctlHTMLPEDDest.Name = "ctlHTMLPEDDest";
            this.ctlHTMLPEDDest.Size = new System.Drawing.Size(100, 20);
            this.ctlHTMLPEDDest.TabIndex = 34;
            this.ctlHTMLPEDDest.Text = "C:\\Documents and Settings\\Pavel Bure\\My Documents\\Visual Studio 2008\\Projects\\Pal" +
                "iReader\\PaliTextReader2\\bin\\Debug\\PED\\";
            this.ctlHTMLPEDDest.Visible = false;
            // 
            // ctlPrepare
            // 
            this.ctlPrepare.Location = new System.Drawing.Point(292, 440);
            this.ctlPrepare.Name = "ctlPrepare";
            this.ctlPrepare.Size = new System.Drawing.Size(75, 23);
            this.ctlPrepare.TabIndex = 35;
            this.ctlPrepare.Text = "Prepare PED";
            this.ctlPrepare.UseVisualStyleBackColor = true;
            this.ctlPrepare.Visible = false;
            this.ctlPrepare.Click += new System.EventHandler(this.ctlPrepare_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(413, 443);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 36;
            this.button2.Text = "Generate test";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // MainWnd
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(544, 481);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.ctlPrepare);
            this.Controls.Add(this.ctlHTMLPEDDest);
            this.Controls.Add(this.ctlHTMLPEDSource);
            this.Controls.Add(this.ctlDictionary);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.ctlDictionaryPath);
            this.Controls.Add(this.ctlGenerateFiles);
            this.Controls.Add(this.ctlPagesOther);
            this.Controls.Add(this.ctlPagesThai);
            this.Controls.Add(this.ctlPagesMyanmar);
            this.Controls.Add(this.ctlPagesVRI);
            this.Controls.Add(this.ctlPagesPTS);
            this.Controls.Add(this.ctlOtherContent);
            this.Controls.Add(this.ctlMula);
            this.Controls.Add(this.ctlTika);
            this.Controls.Add(this.ctlAtthakatha);
            this.Controls.Add(this.ctlOther);
            this.Controls.Add(this.ctlAbidhamma);
            this.Controls.Add(this.ctlSutta);
            this.Controls.Add(this.ctlVinaya);
            this.Controls.Add(this.ctlStartConversion2);
            this.Controls.Add(this.ctlConversionProgress);
            this.Controls.Add(this.ctlMessage);
            this.Controls.Add(this.ctlDiffsHandling);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.ctlPlatform);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.ctlDestFolderBrowse);
            this.Controls.Add(this.ctlDestFolder);
            this.Controls.Add(this.ctlCSCDFolder);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.ctlCSCDBrowse);
            this.Controls.Add(this.label1);
            this.Name = "MainWnd";
            this.Text = "CSCD Book converter";
            this.Load += new System.EventHandler(this.MainWnd_Load);
            ((System.ComponentModel.ISupportInitialize)(this.ctlErrorProvider)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.m_objDS)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new MainWnd());
		}

		private void MainWnd_Load(object sender, System.EventArgs e)
		{
            ctlDictionary.DataSource = m_objDictionariesTA.GetData();
			ctlDiffsHandling.SelectedIndex=1;
            ctlDictionary.SelectedIndex = 1;
		}

		private void ctlCSCDBrowse_Click(object sender, System.EventArgs e)
		{
			if(ctlBrowseFolder.ShowDialog()==DialogResult.OK)
				ctlCSCDFolder.Text=ctlBrowseFolder.SelectedPath;
		}

		private void ctlDestFolderBrowse_Click(object sender, System.EventArgs e)
		{
			if(ctlBrowseFolder.ShowDialog()==DialogResult.OK)
				ctlDestFolder.Text=ctlBrowseFolder.SelectedPath;
		}

		private string DiffsEvaluator(Match objDiffMatch)
		{//strip all book references in parentheses except (?)
			return Regex.Replace(objDiffMatch.Value,@"\ *\([^\?]*?\)\ *","");
		}

		private string FormatName(string strName)
		{
			return Regex.Replace(strName,@"([^ \d])0([ \)\.\r])","$1.$2");
		}

		private void ctlCSCDFolder_Validating(object sender, System.ComponentModel.CancelEventArgs e)
		{
			ctlErrorProvider.SetError(ctlCSCDFolder,
				IsCSCDFolderValid ? "" : "this should point to CSCD root directory");
		}

		private void ctlDestFolder_Validating(object sender, System.ComponentModel.CancelEventArgs e)
		{
			ctlErrorProvider.SetError(ctlDestFolder,
				IsDestFolderValid ? "" : "must be a valid directory");			
		}

		private bool IsCSCDFolderValid
		{
			get
			{
				return (ctlCSCDFolder.Text!="" && Directory.Exists(ctlCSCDFolder.Text+@"\CSCD"));
			}
		}

		private bool IsDestFolderValid
		{
			get
			{
				return (ctlDestFolder.Text!="" && Directory.Exists(ctlDestFolder.Text));
			}
		}

		private void ctlStartConversion2_Click(object sender, System.EventArgs e)
		{
			Validate();
			
			if(IsCSCDFolderValid && IsDestFolderValid)
			{
				try
				{
					ctlStartConversion2.Enabled=false;
					if(!ctlCSCDFolder.Text.EndsWith(@"\"))
						ctlCSCDFolder.Text+=@"\";

					if(!ctlDestFolder.Text.EndsWith(@"\"))
						ctlDestFolder.Text+=@"\";
					
					FileStream fs=File.Open(ctlCSCDFolder.Text+@"\CSCD\open.ale",FileMode.Open,FileAccess.Read);
					byte[] arrContent=new byte[fs.Length];
					fs.Read(arrContent,0,(int)fs.Length);
					fs.Close();

					AalekhDecoder objDecoder=new AalekhDecoder();
					char[] arrDecoded=objDecoder.AalekhToUnicode(arrContent,false,false);
					string strFileContent=new string(arrDecoded);
					MatchCollection mc=Regex.Matches(strFileContent,@"^(\d{4})~([^#]*)#([^#]+)",RegexOptions.IgnoreCase | RegexOptions.Multiline);

					ArrayList objIndexList=new ArrayList(3000);
                    List<NodePageRange> arrPageRange = new List<NodePageRange>(500);

                    m_objCollectionsTA.Fill(m_objDS.Collections);
                    //m_objFilesTA.Adapter.RowUpdated += new System.Data.SqlServerCe.SqlCeRowUpdatedEventHandler(Adapter_RowUpdated);
                    //m_objNodesTA.Adapter.RowUpdated+=new System.Data.SqlServerCe.SqlCeRowUpdatedEventHandler(Adapter_RowUpdated);

                    m_objFilesTA.Adapter.InsertCommand.Connection.Open();
                    m_objNodesTA.Adapter.InsertCommand.Connection.Open();
                    m_objPTSPagesTA.Adapter.InsertCommand.Connection.Open();

					if(ctlVinaya.Checked)
                        CreatePitakaContent2(mc, "1", "Vinaya pitaka");

					if(ctlSutta.Checked)
                        CreatePitakaContent2(mc, "2", "Sutta pitaka");

					if(ctlAbidhamma.Checked)
                        CreatePitakaContent2(mc, "3", "Abhidhamma pitaka");

					if(ctlOther.Checked)
                        CreatePitakaContent2(mc, "4", "Others");

                    m_objFilesTA.Adapter.InsertCommand.Connection.Close();
                    m_objNodesTA.Adapter.InsertCommand.Connection.Close();
                    m_objPTSPagesTA.Adapter.InsertCommand.Connection.Close();

					ctlMessage.Text="Done!";
				}
				catch(Exception ex)
				{
					MessageBox.Show(ex.Message+"\r\n"+ex.StackTrace);
				}
				finally
				{
					ctlStartConversion2.Enabled=true;
				}
			}					
		}

        void Adapter_RowUpdated(object sender, System.Data.SqlServerCe.SqlCeRowUpdatedEventArgs e)
        {
            SQLCEIDhelper.SetPrimaryKey(e.Command.Connection, e);
        }

        private void CreatePitakaContent2(MatchCollection mc, string strPitakaID, string strPitakaName)
		{
            contentsDS.NodesRow objPitakaNode = m_objDS.Nodes.NewNodesRow();
            objPitakaNode.NodeTitle = strPitakaName;
            objPitakaNode.HasChildren = true;
            objPitakaNode.NodeID=AddNode(objPitakaNode);
            objPrevNode = objPitakaNode;
            

            //IndexNode objPitakaNode=new IndexNode(0,m_nNodeCounter++,strPitakaName,true,-1,0xFF);
            //objIndexList.Add(objPitakaNode);

			ctlMessage.Text="Converting "+strPitakaName;
			ctlConversionProgress.Maximum=mc.Count;
			ctlConversionProgress.Value=0;
			ctlConversionProgress.Step=1;
			
			//IndexNode objNikayaNode=null;
            contentsDS.NodesRow objNikayaNode = null;

			foreach(Match m in mc)
			{
				if(m.Groups[1].Value.Substring(0,1)==strPitakaID)
				{
					string strName=FormatName(m.Groups[3].Value);

					if(Regex.IsMatch(m.Groups[1].Value,@"\d{2}00")) //nikaya
					{
                        objNikayaNode=m_objDS.Nodes.NewNodesRow();
                        objNikayaNode.ParentID = objPitakaNode.NodeID;
                        objNikayaNode.NodeTitle = strName;
                        objNikayaNode.HasChildren = true;
                        objNikayaNode.NodeID=AddNode(objNikayaNode);
                        objPrevNode = objNikayaNode;

                        //objNikayaNode=new IndexNode(objPitakaNode.NodeID,m_nNodeCounter++,strName,true,-1,0xFF);
                        //objIndexList.Add(objNikayaNode);
					}
					else //book
					{
						string strAalekhFileName=m.Groups[2].Value;

						bool bConvert=true;
						if(!ctlMula.Checked && strAalekhFileName.IndexOf("mul")>-1)
							bConvert=false;

						if(!ctlAtthakatha.Checked && strAalekhFileName.IndexOf("att")>-1)
							bConvert=false;

						if(!ctlTika.Checked && strAalekhFileName.IndexOf("tik")>-1)
							bConvert=false;

						if(!ctlOtherContent.Checked && strAalekhFileName.IndexOf("nrf")>-1)
							bConvert=false;

						if(bConvert)
						{
                            contentsDS.FilesRow objFile = m_objDS.Files.NewFilesRow();
                            objFile.FileName = strAalekhFileName;
                            m_objFilesTA.Insert(objFile.FileName,null);

                            SqlCeCommand cmdGetIdentity = new SqlCeCommand("SELECT @@IDENTITY", m_objFilesTA.Connection);
                            m_nFileID = Convert.ToInt32(cmdGetIdentity.ExecuteScalar());

                            contentsDS.NodesRow objBookNode = m_objDS.Nodes.NewNodesRow();
                            if (objNikayaNode != null)
                                objBookNode.ParentID = objNikayaNode.NodeID;
                            else
                                objBookNode.ParentID = objPitakaNode.NodeID;

                            objBookNode.NodeTitle = strName;
                            objBookNode.HasChildren = true;
                            objBookNode.FileID = m_nFileID;

                            objBookNode.NodeID=AddNode(objBookNode);
                            objPrevNode = objBookNode;


                            //IndexNode objBookNode=null;
                            //if(objNikayaNode!=null)
                            //    objBookNode=new IndexNode(objNikayaNode.NodeID,m_nNodeCounter++,strName,true,-1,0xFF);							
                            //else
                            //    objBookNode=new IndexNode(objPitakaNode.NodeID,m_nNodeCounter++,strName,true,-1,0xFF);							
						
                            //objIndexList.Add(objBookNode);

                            ConvertBook2(strAalekhFileName, objBookNode, objFile);						
						}
					}
				}
				ctlConversionProgress.PerformStep();
				Application.DoEvents();
			}
		}

        private void ConvertBook2(string strAalekhFileName, contentsDS.NodesRow objParentNode, contentsDS.FilesRow objFile)
		{
			FileStream fs=File.Open(ctlCSCDFolder.Text+@"CSCD\"+strAalekhFileName,FileMode.Open,FileAccess.Read);
			byte[] arrContent=new byte[fs.Length];
			fs.Read(arrContent,0,(int)fs.Length);
			fs.Close();

			AalekhDecoder objDecoder=new AalekhDecoder();
			char[] arrDecoded=objDecoder.AalekhToUnicode(arrContent,false,true);	
			string strFileContent=new string(arrDecoded);

            //PTS страницы перекинуть в таблицу File!!

            if (SavePageRange(strFileContent, m_nFileID))
            {
                int? nCollectionID=null;

                foreach(contentsDS.CollectionsRow objCollRow in m_objDS.Collections)
                {
                    if (!objCollRow.IsFilePatternNull() && Regex.IsMatch(strAalekhFileName, objCollRow.FilePattern,RegexOptions.IgnoreCase))
                        nCollectionID = objCollRow.CollectionID;
                }

                m_objFilesTA.Update(strAalekhFileName, nCollectionID, m_nFileID);
            }

            //objChapterNode.PTSVolumeID=;

			string[] arrChapters=Regex.Split(strFileContent,@"\\c11");
            m_nParagraphID = 0;

            if (arrChapters.Length > 1)
            {//split the book into chapters
                //objParentNode.HasChildren=true;
                //m_objNodesTA.Update(objParentNode);

                for (int nChapterCounter = 1; nChapterCounter < arrChapters.Length; nChapterCounter++)
                {
                    Match m = Regex.Match(arrChapters[nChapterCounter], ".*", RegexOptions.Multiline);//chapter name
                    string strChapterName = m.Value.Trim();

                    strChapterName = Regex.Replace(strChapterName, @"[BVPTO]\d\.\d{4}", "");
                    strChapterName = Regex.Replace(strChapterName, @"{.*?}", "").Trim();

                    contentsDS.NodesRow objChapterNode = m_objDS.Nodes.NewNodesRow();
                    objChapterNode.ParentID = objParentNode.NodeID;
                    objChapterNode.NodeTitle = strChapterName;
                    objChapterNode.HasChildren = Regex.IsMatch(arrChapters[nChapterCounter],@"(\\c1(?:3|4))");
                    objChapterNode.FileID = objParentNode.FileID;
                    m_nParagraphID++;
                    objChapterNode.BookmarkName = m_nParagraphID;

                    arrChapters[nChapterCounter] = Regex.Replace(arrChapters[nChapterCounter], "^([^\r]*)", "<a name=\"p" + m_nParagraphID.ToString() + "\">$1</a>\r", RegexOptions.Singleline);

                    objChapterNode.NodeID=AddNode(objChapterNode);
                    objPrevNode = objChapterNode;

                    m_nParentNodeID = objChapterNode.NodeID;
                    m_nC13NodeID = -1;
                    arrChapters[nChapterCounter] = Regex.Replace(arrChapters[nChapterCounter], @"(\\c1(?:3|4)) (.+)", new MatchEvaluator(ParagraphEvaluator3), RegexOptions.Multiline | RegexOptions.IgnoreCase);
                }
            }

            if (ctlGenerateFiles.Checked)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string strChapter in arrChapters)
                {
                    sb.Append(strChapter);
                    sb.Append(@"\c11");
                }

                strFileContent = sb.ToString();
                strFileContent.Substring(0, strFileContent.Length - 5);

                if (!ctlPagesPTS.Checked)
                    strFileContent = Regex.Replace(strFileContent, "P\\d\\.\\d{4}", "");

                if (!ctlPagesVRI.Checked)
                    strFileContent = Regex.Replace(strFileContent, "V\\d\\.\\d{4}", "");

                if (!ctlPagesMyanmar.Checked)
                    strFileContent = Regex.Replace(strFileContent, "B\\d\\.\\d{4}", "");

                if (!ctlPagesThai.Checked)
                    strFileContent = Regex.Replace(strFileContent, "T\\d\\.\\d{4}", "");

                if (!ctlPagesOther.Checked)
                    strFileContent = Regex.Replace(strFileContent, "O\\d\\.\\d{4}", "");

                switch (ctlDiffsHandling.SelectedIndex)
                {
                    case 1:
                        strFileContent = Regex.Replace(strFileContent, @"\{.*?\}", new MatchEvaluator(DiffsEvaluator), RegexOptions.Singleline);
                        break;
                    case 2:
                        strFileContent = Regex.Replace(strFileContent, @"\{.*?\}", "", RegexOptions.Singleline);
                        break;
                }

                AalekhFormatter objFormatter = new AalekhFormatter(strFileContent.ToCharArray());
                char[] arrHTML = objFormatter.ToHTML();

                byte[] arrFileMarker = { 0xEF, 0xBB, 0xBF };
                byte[] arrChapterBuffer = System.Text.Encoding.UTF8.GetBytes(arrHTML);

                FileStream fsBook = new FileStream(ctlDestFolder.Text + strAalekhFileName + ".htm", FileMode.Create);
                BinaryWriter bwBook = new BinaryWriter(fsBook, Encoding.UTF8);
                bwBook.Write(arrFileMarker, 0, 3);
                bwBook.Write(arrChapterBuffer, 0, arrChapterBuffer.Length);
                bwBook.Close();
                fsBook.Close();
            }
		}

        private bool SavePageRange(string strFileContent, int FileID)
        {
            bool bRetVal = false;

            MatchCollection mcPages = Regex.Matches(strFileContent, @"P(\d)\.(\d{4})");
            ushort nMinPage = 0;
            ushort nMaxPage = 0;
            ushort nVolumeID = 0;
            ushort nOldVolumeID = 0;

            foreach (Match mPage in mcPages)
            {
                nVolumeID = ushort.Parse(mPage.Groups[1].Value);

                if (nOldVolumeID == 0)
                    nOldVolumeID = nVolumeID;

                if (nVolumeID != nOldVolumeID)
                {
                    bRetVal = true;
                    m_objPTSPagesTA.Insert(FileID, nOldVolumeID, nMinPage, nMaxPage);
                    nMinPage = 0;
                    nMaxPage = 0;
                    nOldVolumeID = 0;
                }

                ushort nPage = ushort.Parse(mPage.Groups[2].Value);

                if (nMinPage == 0 || nMinPage > nPage)
                    nMinPage = nPage;

                if (nMaxPage == 0 || nMaxPage < nPage)
                    nMaxPage = nPage;
            }

            if (mcPages.Count > 0)
            {
                bRetVal = true;
                m_objPTSPagesTA.Insert(FileID, nVolumeID, nMinPage, nMaxPage);
            }

            return bRetVal;
        }




        private string ParagraphEvaluator3(Match objParaMatch)
        {
            m_nParagraphID++;

            //strip page numbers
            string strParaName = Regex.Replace(objParaMatch.Groups[2].Value, @"[BVPTO]\d\.\d{4}", "");
            //strip differences
            strParaName = Regex.Replace(strParaName, @"{.*?}", "").Trim();
            //strip formatting that gets here in Jataka atthakatha
            strParaName = Regex.Replace(strParaName, @"\\c\d+", "").Trim();
            int ParentID = m_nParentNodeID;

            if (objParaMatch.Groups[1].Value == "\\c14" && m_nC13NodeID != -1)
            {
                ParentID = m_nC13NodeID;
                if (objPrevNode.NodeID == m_nC13NodeID)
                {
                    objPrevNode.HasChildren = true;
                    m_objNodesTA.Update(objPrevNode.ParentID, 
                        objPrevNode.NodeTitle, true, objPrevNode.BookmarkName,
                        objPrevNode.FileID, Diacritics.ConvertDiac(objPrevNode.NodeTitle), 
                        objPrevNode.NodeID);
                }
            }

            contentsDS.NodesRow objIndexNode = m_objDS.Nodes.NewNodesRow();
            objIndexNode.ParentID = ParentID;
            objIndexNode.NodeTitle = strParaName;
            objIndexNode.HasChildren = false;
            objIndexNode.FileID = m_nFileID;
            objIndexNode.BookmarkName = m_nParagraphID;
            objIndexNode.NodeID=AddNode(objIndexNode);
            objPrevNode = objIndexNode;

            if (objParaMatch.Groups[1].Value == "\\c13")
                m_nC13NodeID = objIndexNode.NodeID;

            return objParaMatch.Groups[1].Value + "<a name=\"p" + m_nParagraphID.ToString() + "\">" + objParaMatch.Groups[2].Value.Trim() + "</a>\r";
        }

        private int AddNode(contentsDS.NodesRow objRow)
        {
            m_objNodesTA.Insert(objRow.IsParentIDNull() ? null : (int?)objRow.ParentID, 
                objRow.NodeTitle, 
                objRow.HasChildren, 
                objRow.IsBookmarkNameNull() ? null : (int?)objRow.BookmarkName,
                objRow.IsFileIDNull() ? null : (int?)objRow.FileID,
                Diacritics.ConvertDiac(objRow.NodeTitle));

            SqlCeCommand cmdGetIdentity = new SqlCeCommand("SELECT @@IDENTITY", m_objNodesTA.Adapter.InsertCommand.Connection);

            return Convert.ToInt32(cmdGetIdentity.ExecuteScalar());
        }

        private void Update(contentsDS.NodesRow objRow)
        {
            m_objNodesTA.Update(objRow);
        }

        #region тухлятина
        private void GetPageRange(string strFileContent, out ushort VolumeID, out ushort MinPage, out ushort MaxPage, out bool MultiVolume)
        {
            //find minimum and maximum PTS page number for this node
            MatchCollection mcPages = Regex.Matches(strFileContent, @"P(\d)\.(\d{4})");
            ushort nMinPage = 0;
            ushort nMaxPage = 0;
            ushort nVolumeID = 0;
            ushort nOldVolumeID = 0;
            MultiVolume = false;

            foreach (Match mPage in mcPages)
            {
                nVolumeID = ushort.Parse(mPage.Groups[1].Value);

                if (nOldVolumeID == 0)
                    nOldVolumeID = nVolumeID;

                if (nVolumeID != nOldVolumeID)
                    MultiVolume = true;

                ushort nPage = ushort.Parse(mPage.Groups[2].Value);

                if (nMinPage == 0 || nMinPage > nPage)
                    nMinPage = nPage;

                if (nMaxPage == 0 || nMaxPage < nPage)
                    nMaxPage = nPage;
            }

            VolumeID = nVolumeID;
            MinPage = nMinPage;
            MaxPage = nMaxPage;
        }

        private void ConvertChapter2(int ParentNodeID, string strChapterName, string strFileName, string strChapterContent, ArrayList objIndexList, List<NodePageRange> arrPageRange)
		{
			strChapterName=Regex.Replace(strChapterName,@"[BVPTO]\d\.\d{4}","");
			strChapterName=Regex.Replace(strChapterName,@"{.*?}","").Trim();

			m_nParagraphID=0;
			m_arrChaptersList=new ArrayList();
			m_nParentNodeID=m_nNodeCounter++;
			m_nC13NodeID=-1;

			strChapterContent=Regex.Replace(strChapterContent,@"(\\c1(?:3|4)) (.+)",new MatchEvaluator(ParagraphEvaluator2),RegexOptions.Multiline | RegexOptions.IgnoreCase);

			if(!ctlPagesPTS.Checked)
				strChapterContent = Regex.Replace(strChapterContent, "P\\d\\.\\d{4}", "");
			
			if(!ctlPagesVRI.Checked)
				strChapterContent = Regex.Replace(strChapterContent, "V\\d\\.\\d{4}", "");

			if(!ctlPagesMyanmar.Checked)
				strChapterContent = Regex.Replace(strChapterContent, "B\\d\\.\\d{4}", "");

			if(!ctlPagesThai.Checked)
				strChapterContent = Regex.Replace(strChapterContent, "T\\d\\.\\d{4}", "");

			if(!ctlPagesOther.Checked)
				strChapterContent = Regex.Replace(strChapterContent, "O\\d\\.\\d{4}", "");

			switch(ctlDiffsHandling.SelectedIndex)
			{
				case 1:
					strChapterContent=Regex.Replace(strChapterContent,@"\{.*?\}",new MatchEvaluator(DiffsEvaluator),RegexOptions.Singleline);
					break;
				case 2:
					strChapterContent = Regex.Replace(strChapterContent, @"\{.*?\}", "",RegexOptions.Singleline);
					break;
			}

            //find minimum and maximum PTS page number for this node
            MatchCollection mcPages=Regex.Matches(strChapterContent, @"P(\d)\.(\d{4})");
            ushort nMinPage = 0;
            ushort nMaxPage = 0;
            ushort nVolumeID = 0;
            foreach (Match mPage in mcPages)
            {
                nVolumeID = ushort.Parse(mPage.Groups[1].Value);
                ushort nPage = ushort.Parse(mPage.Groups[2].Value);

                if (nMinPage == 0 || nMinPage > nPage)
                    nMinPage = nPage;

                if (nMaxPage == 0 || nMaxPage < nPage)
                    nMaxPage = nPage;                
            }

            arrPageRange.Add(new NodePageRange((ushort)m_nParentNodeID, nVolumeID,nMinPage, nMaxPage));

			//now format it
			AalekhFormatter objFormatter=new AalekhFormatter(strChapterContent.ToCharArray());
			char[] arrHTML=objFormatter.ToHTML();			

			//save content to archive
			byte[] arrFileMarker={0xEF,0xBB,0xBF};
			byte[] arrChapterBuffer=System.Text.Encoding.UTF8.GetBytes(arrHTML);
			
			if(m_objLibraryStream==null)
			{
				m_nZipFileIndex=0;
				string strLibFileName=String.Format("PocketLib{0}.zip",m_nLibFileIndex);
				m_objLibraryStream=new ZipOutputStream(File.Create(ctlDestFolder.Text+strLibFileName));
				m_objLibraryStream.SetLevel(5);
			}

			ZipEntry objChapterEntry=new ZipEntry(strFileName);
			m_objLibraryStream.PutNextEntry(objChapterEntry);
			m_objLibraryStream.Write(arrFileMarker,0,3);
			m_objLibraryStream.Write(arrChapterBuffer,0,arrChapterBuffer.Length);
			//save index to archive
			IndexNode objIndexNode=new IndexNode(ParentNodeID,m_nParentNodeID,strChapterName,(m_nParagraphID>0),m_nZipFileIndex,m_nLibFileIndex);
			objIndexList.Add(objIndexNode);
			foreach(IndexNode objParagraphNode in m_arrChaptersList)
			{
				objParagraphNode.ZipFileIndex=m_nZipFileIndex;
				objParagraphNode.LibFileIndex=m_nLibFileIndex;
				objIndexList.Add(objParagraphNode);
			}

			if(m_nZipFileIndex>499)
			{
				m_objLibraryStream.Finish();
				m_objLibraryStream.Close();
				m_objLibraryStream=null;
				m_nLibFileIndex++;
			}

			m_nZipFileIndex++;
		}

		private string ParagraphEvaluator2(Match objParaMatch)
		{
			m_nParagraphID++;

			//strip page numbers
			string strParaName=Regex.Replace(objParaMatch.Groups[2].Value,@"[BVPTO]\d\.\d{4}","");
			//strip differences
			strParaName=Regex.Replace(strParaName,@"{.*?}","").Trim();
			//strip formatting that gets here in Jataka atthakatha
			strParaName=Regex.Replace(strParaName,@"\\c\d+","").Trim();
			int ParentID=m_nParentNodeID;

			if(objParaMatch.Groups[1].Value=="\\c14" && m_nC13NodeID!=-1)
			{
				ParentID=m_nC13NodeID;
				IndexNode objPrevNode=(IndexNode)m_arrChaptersList[m_arrChaptersList.Count-1];
				if(objPrevNode.NodeID==m_nC13NodeID)
					objPrevNode.HasChildren=true;
			}

			IndexNode objIndexNode=new IndexNode(ParentID,m_nNodeCounter++,strParaName,false,-1,"p"+m_nParagraphID.ToString(),m_nLibFileIndex);
			m_arrChaptersList.Add(objIndexNode);	
			
			if(objParaMatch.Groups[1].Value=="\\c13")
				m_nC13NodeID=objIndexNode.NodeID;

			return objParaMatch.Groups[1].Value+"<a name=\"p"+m_nParagraphID.ToString()+"\">"+objParaMatch.Groups[2].Value.Trim()+"</a>";
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            string path = ctlDictionaryPath.Text;
            
            if (File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                StreamReader rs = new StreamReader(fs);
                string line;

                m_objContentsTA.Connection.Open();

                while ((line = rs.ReadLine()) != null)
                {
                    String key = "";
                    String entry = "";
                    if (line != "")
                    {
                        //key = line.Split(' ')[0];
                        key = line.Split('\t')[0];

                        if (key.Length + 1 < line.Length)
                            entry = line.Substring(key.Length + 1);

                        if (key != null && key != "")
                            m_objContentsTA.Insert(key, entry,
                                Diacritics.ConvertDiac(key), Diacritics.ConvertDiac(entry),
                                (int)ctlDictionary.SelectedValue);

                        //key = line.Trim();

                        //if ((line = rs.ReadLine()) != null)
                        //{
                        //    if (line != "")
                        //    {
                        //        entry = line.Trim();
                        //        m_objContentsTA.Insert(key, entry,
                        //            Diacritics.ConvertDiac(key), Diacritics.ConvertDiac(entry),
                        //            (int)ctlDictionary.SelectedValue);
                        //    }
                        //}
                    }
                }

                m_objContentsTA.Connection.Close();

                rs.Close();
                fs.Close();
            }
        }

        private void ctlPrepare_Click(object sender, EventArgs e)
        {
            string strSourcepath = ctlHTMLPEDSource.Text;
            string strDestPath = ctlHTMLPEDDest.Text;

            if (File.Exists(strSourcepath))
            {
                FileStream fs = new FileStream(strSourcepath, FileMode.Open, FileAccess.Read);
                StreamReader rs = new StreamReader(fs);
                string strContent=rs.ReadToEnd();
                rs.Close();
                fs.Close();

                string[] arrStrings = strContent.Split(new string[] { "<span class=letter>" }, StringSplitOptions.RemoveEmptyEntries);

                string arrHead = arrStrings[0].Split(new string[] { "<span class=page>" }, StringSplitOptions.RemoveEmptyEntries)[0];

                for (int i = 1; i < arrStrings.Length; i++)
                {
                    FileStream fsDest = new FileStream(strDestPath+i.ToString("00")+".htm", FileMode.Create, FileAccess.Write);
                    StreamWriter swDest = new StreamWriter(fsDest);
                    swDest.Write(arrHead);

                    swDest.Write("<span class=letter>");
                    swDest.Write(arrStrings[i]);

                    if (i != arrStrings.Length-1)
                        swDest.Write("</BODY></HTML>");

                    swDest.Close();
                    fsDest.Close();
                }


            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
            FileStream fs = File.Open(ctlCSCDFolder.Text + @"\CSCD\e0201n.nrf", FileMode.Open, FileAccess.Read);
            byte[] arrContent = new byte[fs.Length];
            fs.Read(arrContent, 0, (int)fs.Length);
            int nLength = (int)fs.Length;
            fs.Close();

/*
            int nBegin = 0;
            
            StringBuilder sb = new StringBuilder();

            AalekhDecoder objDecoder = new AalekhDecoder();

            for (int i = 0; i < nLength; i++)
            {
                if (arrContent[i] == 0x0d)
                {
                    char[] arrDecoded = objDecoder.AalekhToUnicode(arrContent,nBegin,i, false, false);

                    if (i > nBegin)
                    {
                        //запись декодированной строки в fs
                        for (int j = nBegin; j < i; j++)
                        {
                            sb.AppendFormat("{0:x} ", arrContent[j]);
                        }
                        sb.Append("\r\n");
                        sb.Append(arrDecoded);
                        sb.Append("\r\n\r\n");
                    }
                    nBegin = i + 2;
                }
            }

            FileStream fs2 = File.Open(ctlDestFolder.Text + "\\e0201n.nrf.txt", FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs2);
            sw.Write(sb.ToString());
            sw.Close();
            fs2.Close();
*/

            AalekhDecoder objDecoder = new AalekhDecoder();
            char[] arrDecoded = objDecoder.AalekhToUnicode(arrContent, false, true);
            string strFileContent = new string(arrDecoded);

            AalekhFormatter objFormatter = new AalekhFormatter(strFileContent.ToCharArray());
            char[] arrHTML = objFormatter.ToHTML();


            byte[] arrFileMarker = { 0xEF, 0xBB, 0xBF };
            byte[] arrChapterBuffer = System.Text.Encoding.UTF8.GetBytes(arrHTML);

            FileStream fsBook = new FileStream(ctlDestFolder.Text + "\\e0201n.nrf.htm", FileMode.Create);
            BinaryWriter bwBook = new BinaryWriter(fsBook, Encoding.UTF8);
            bwBook.Write(arrFileMarker, 0, 3);
            bwBook.Write(arrChapterBuffer, 0, arrChapterBuffer.Length);
            bwBook.Close();
            fsBook.Close();

            MessageBox.Show("Done");
        }
    }
}
